package com.sunyard.layoutit.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.sunyard.layoutit.common.DatabaseConfig;
import com.sunyard.layoutit.dao.DaoFactory;
import com.sunyard.layoutit.dao.RepositoryBoxDao;

public class InitBoxData {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		System.out.println("当前JDK版本 : "+System.getProperty("java.version"));
		DatabaseConfig.init(null);
		excute("data-box-group1.xml","group1");
		excute("data-box-group2.xml","group2");
		excute("data-box-group3.xml","group3");
//		is.close() ;
	}
	
	public static void excute(String filename,String groupname)throws Exception {
		System.out.println("当前JDK版本 : "+System.getProperty("java.version"));
		
		String path = InitBoxData.class.getProtectionDomain().getCodeSource().getLocation().getPath() ;
		File file = new File(path+"database"+File.separator+filename);
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder dombuilder =dbf.newDocumentBuilder();
		InputStream is= new  FileInputStream(file); 
		Document doc= dombuilder.parse(is);
		Element root = doc.getDocumentElement();
		System.out.println(root.getNodeName());//根节点
		NodeList boxs = root.getChildNodes();
		iterator(boxs,groupname);
		
//		is.close() ;
	
	};
	
	public static void iterator(NodeList boxs,String groupname){
		System.out.println(boxs.getLength());
		for (int i = 0; i < boxs.getLength(); i++) {
			System.out.println(i);
			Node box_node = boxs.item(i);
			if(box_node instanceof Element){
				Element box = (Element)box_node;
				System.out.println(box.getNodeName());
				System.out.println(box.getChildNodes().getLength());
				NamedNodeMap attrs = box.getAttributes();
				System.out.println(attrs.getLength());
				String attr_class = attrs.getNamedItem("class").getNodeValue();
				if("box box-element ui-draggable".equals(attr_class)){
					//盒模型节点
					NodeList infos = box.getChildNodes() ;
					Map<String,Element> map = new HashMap<String,Element>();
					for(int j = 0;j<infos.getLength();j++){
						Node info_node = infos.item(j);
						if(info_node instanceof Element){
							Element info = (Element)info_node;
							NamedNodeMap info_attrs = info.getAttributes();
							String info_attrs_class = info_attrs.getNamedItem("class").getNodeValue();
							System.out.println("info_attrs_class="+info_attrs_class);
							if(info_attrs_class.startsWith("view")){//TODO
								map.put("view", info);
							}else{
								map.put(info_attrs_class, info);
							}
							
						}
					}
					System.out.println("map.size="+map.size());
					Element preview_node = map.get("preview");
					Element view_node = map.get("view");
					Element configuration = map.get("configuration");
					
					if(null == preview_node){
//						System.out.println(box.getTextContent()); ;
//						System.out.println(doc2String(box));
					}
//					String preview_text = doc2String(preview_node) ;
					String preview_text = preview_node.getTextContent().trim() ;
					System.err.println("preview_text : "+preview_text);
					String view_outter_html = doc2String(view_node).trim() ;
					String view_innerhtml = view_outter_html.trim();
					System.err.println("view_html : "+view_innerhtml);
					
					List<String> list = new ArrayList<String>();
					if(null != configuration){
						NodeList cfg_list = configuration.getChildNodes() ;
						for(int j = 0;j<cfg_list.getLength();j++){
							System.out.println(j);
							Node cfg_node = cfg_list.item(j);
							if(cfg_node instanceof Element){
								Element cfg = (Element)cfg_node ;
								String cfg_html = doc2String(cfg).trim();
								System.err.println("cfg : "+cfg_html);
								list.add(cfg_html);
							}
						}
					}
					RepositoryBoxDao dao = DaoFactory.getRepositoryBoxDao() ;
					dao.transInsert(preview_text, view_innerhtml, list, groupname) ;
//					configuration
				}
				System.out.println(attr_class);
			}else{
				System.out.println("TEXT_NODE #text");
			}

//			box.getAttributes()
		}
	}

    private static TransformerFactory tFactory = TransformerFactory.newInstance();
    private static Transformer transformer = null;
    
	public static String doc2String(org.w3c.dom.Element document)
    {
		
        String s = "";
        try
        {
        	Thread.sleep(100);
        	if(null == transformer){
        		transformer = tFactory.newTransformer() ;
        	}
            Source source = new DOMSource(document);
            StringWriter out = new StringWriter();
            Result output = new StreamResult(out);
            transformer.transform(source, output);
            out.flush();
            s = out.toString();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return s.substring(38);
    }
}
